package com.sinodata.bsm.cicp.collector.tomcat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class TomcatGlobalRequestProcessorCollector extends Collector {
    private static Logger logger = Logger.getLogger(TomcatGlobalRequestProcessorCollector.class);
    private final HashMap requestPerMin = new HashMap();

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        //        String port = this.getParamMap().get("端口");
        String port = this.getParamMap().get("Port");
        String[] propertyNames = new String[] { "requestCount", "bytesSent", "bytesReceived", "processingTime", "errorCount", "maxTime" };
        Object propertyValues[] = null;
        List<String> keys = new ArrayList<String>();
        //        String name = this.getParamMap().get("名称").trim();
        String name = this.getParamMap().get("Name").trim();

        long time = System.currentTimeMillis();
        String key = name + ":" + ip;

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            //connector = JmxUtil.getConnection(JmxUtil.TOMCAT, ip + ":" + port);
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            ObjectName tomcatEngine = new ObjectName("Catalina:type=GlobalRequestProcessor,*");
            Set<ObjectName> set = connection.queryNames(tomcatEngine, null);
            for (ObjectName obj : set) {
                if (obj.getKeyProperty("name").equals(name)) {
                    ObjectName objname = new ObjectName(obj.getCanonicalName());
                    propertyValues = JmxUtil.getAttribute(connection, objname, propertyNames);
                    String[] temp = new String[propertyValues.length + 1];
                    for (int i = 0; i < propertyValues.length; i++) {
                        temp[i] = propertyValues[i].toString();
                        propValues[i] = ResPropertyValue.createPropValue(temp[i], propMetas[i]);
                    }
                    if (requestPerMin.get(key) != null) {
                        String tmp = String.valueOf(requestPerMin.get(key));
                        //String[] valueTime = StringUtil.splitStr(tmp, ":");
                        String[] valueTime = tmp.split(":");
                        temp[6] = String.valueOf((Long.parseLong(valueTime[0]) - Long.parseLong(temp[0])) * 1000 * 60 / (time - Long.parseLong(valueTime[1])));
                        if (Long.parseLong(temp[6]) < 0) {
                            temp[6] = "0";
                        }
                        propValues[6] = ResPropertyValue.createPropValue(temp[6], propMetas[6]);
                    }
                    requestPerMin.remove(key);
                    requestPerMin.put(key, temp[0] + ":" + String.valueOf(time));
                    keys.add(createKey(name));

                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            logger.error("when collector TomcatGlobalRequestProcessorCollector: " + e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    //    public Object getKey(ResAttributeValValue[] resourceAttributes, String ip) {
    //        String name = resourceAttributes[0].getAttrValue();
    //        return name;
    //    }

    private String createKey(String name) {
        return name;
    }

    @Override
    public String[] getParamMeta() {
        //        return new String[] { "名称", "端口" };
        return new String[] { "Name", "Port" };
    }

    @Override
    public String[] getPropMeta() {
        //return new String[] { "请求次数", "发送字节", "接收字节数量", "处理时间", "错误数量", "最大处理时间", "每分钟处理请求数量" };
        //return new String[] { "RequestTimes", "SentByte", "ReceiveByteNum", "HandleTime", "ErrorNum", "MaxHandleTime", "HandleRequestsNumPerMinute" };
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7" };
    }

}
